package com.mastercard.card

import java.util.Date;

import com.mastercard.Bank;
import com.mastercard.CreditCard;
import com.mastercard.common.utils.DateUtil;

class CardService {

	def getCardById(id) {
		return CreditCard.findById(id)
	}
	
    def getAllCards() {
		return CreditCard.getAll()
    }
		
	def saveCard (params, user) {
		CreditCard card = null
		if(params.id){
			card = CreditCard.findById(params.id)
		}else{
			card = CreditCard.create()
			card.user = user
		}
		
		if(params.bankId){
			card.bank = Bank.findById(params.bankId)
			card.bank.cards.add(card)
		}
		if(params.name){
			card.name = params.name
		}
		if(params.number){
			card.number = params.number
		}
		if(params.expiryDate){
			Date dt = DateUtil.parseDate(params.expiryDate, "mm/yyyy")
			card.expiryDate = dt
		}
		if(params.ccv2){
			card.ccv2 = params.ccv2
		}
		
		if(!params.id){
			user.creditCards.add(card)
		}
		
		card.save()
	}
	
	def deleteCardById (id) {
		CreditCard card = CreditCard.findById(id)
		if(card){
			card.delete();
		}
	}
}
